package com.bigstar.lolkor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.content.res.AssetManager.AssetInputStream;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigstar.lolkor.ItemList.ViewHolder;
import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class Abbreviation extends ListActivity {

	private static final int SORT_ALL = 0;
	private static final int SORT_CHAMP = 1;
	private static final int SORT_GAME = 2;
	private static final int SORT_ITEM = 3;
	private static final int SORT_SYSTEM = 4;
	Button btn_sort_game;
	Button btn_sort_item;
	Button btn_sort_system;
	Button btn_sort_champ;
	int state = 0;
	AbbrListAdapter adapter;
	EditText et_name;
	private ArrayList<Abbr> game_abb = new ArrayList<Abbr>();
	private ArrayList<Abbr> search_abb = new ArrayList<Abbr>();
	@Override
	protected void onResume() {
		ChampionData.load(this);
		ItemData.load(this);
		Rune.load(this);
		super.onResume();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		ChampionData.load(this);
		ItemData.load(this);
		Rune.load(this);
		loadTurm();
		setContentView(R.layout.abbreviation);
		AdView adview = (AdView) findViewById(R.id.adView);
		AdRequest re = new AdRequest();
		adview.loadAd(re);
		et_name = (EditText) this.findViewById(R.id.et_name);
		et_name.addTextChangedListener(textWatcherInput);
		btn_sort_game = (Button) this.findViewById(R.id.btn_sort_game);
		btn_sort_item = (Button) this.findViewById(R.id.btn_sort_item);
		btn_sort_system = (Button) this.findViewById(R.id.btn_sort_system);
		btn_sort_champ = (Button) this.findViewById(R.id.btn_sort_champ);
		btn_sort_champ = (Button) this.findViewById(R.id.btn_sort_champ);
		btn_sort_champ.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btn_sort_game.setBackgroundResource(R.drawable.abbr_sort_0);
				btn_sort_item.setBackgroundResource(R.drawable.abbr_sort_0);
				btn_sort_system.setBackgroundResource(R.drawable.abbr_sort_0);
				if (state != SORT_CHAMP) {
					state = SORT_CHAMP;
					btn_sort_champ
							.setBackgroundResource(R.drawable.abbr_sort_1);
				} else {
					state = SORT_ALL;
					btn_sort_champ
							.setBackgroundResource(R.drawable.abbr_sort_0);
				}
				search();
				adapter.notifyDataSetChanged();
			}
		});
		btn_sort_game = (Button) this.findViewById(R.id.btn_sort_game);
		btn_sort_game.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (state != SORT_GAME) {
					state = SORT_GAME;
					btn_sort_game.setBackgroundResource(R.drawable.abbr_sort_1);
				} else {
					state = SORT_ALL;
					btn_sort_game.setBackgroundResource(R.drawable.abbr_sort_0);
				}
				btn_sort_item.setBackgroundResource(R.drawable.abbr_sort_0);
				btn_sort_system.setBackgroundResource(R.drawable.abbr_sort_0);
				btn_sort_champ.setBackgroundResource(R.drawable.abbr_sort_0);
				search();
				adapter.notifyDataSetChanged();
			}
		});
		btn_sort_item = (Button) this.findViewById(R.id.btn_sort_item);
		btn_sort_item.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (state != SORT_ITEM) {
					state = SORT_ITEM;
					btn_sort_item.setBackgroundResource(R.drawable.abbr_sort_1);
				} else {
					state = SORT_ALL;
					btn_sort_item.setBackgroundResource(R.drawable.abbr_sort_0);
				}
				btn_sort_game.setBackgroundResource(R.drawable.abbr_sort_0);
				btn_sort_system.setBackgroundResource(R.drawable.abbr_sort_0);
				btn_sort_champ.setBackgroundResource(R.drawable.abbr_sort_0);
				search();
				adapter.notifyDataSetChanged();
			}
		});
		btn_sort_system = (Button) this.findViewById(R.id.btn_sort_system);
		btn_sort_system.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (state != SORT_SYSTEM) {
					state = SORT_SYSTEM;
					btn_sort_system
							.setBackgroundResource(R.drawable.abbr_sort_1);
				} else {
					state = SORT_ALL;
					btn_sort_system
							.setBackgroundResource(R.drawable.abbr_sort_0);
				}
				btn_sort_game.setBackgroundResource(R.drawable.abbr_sort_0);
				btn_sort_item.setBackgroundResource(R.drawable.abbr_sort_0);
				btn_sort_champ.setBackgroundResource(R.drawable.abbr_sort_0);
				search();
				adapter.notifyDataSetChanged();
			}
		});
		search();
		adapter = new AbbrListAdapter(this);
		this.setListAdapter(adapter);
		this.getListView().setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				int resid = 0;
				AlertDialog.Builder alert = new AlertDialog.Builder(Abbreviation.this);
				alert.setTitle(search_abb.get(position).name)
				.setMessage(search_abb.get(position).text);
				alert.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				});
				if(!search_abb.get(position).image.equals("-1")){
					resid = getResources().getIdentifier(search_abb.get(position).image, "drawable", getPackageName());	
					ImageView iv = new ImageView(Abbreviation.this);
					iv.setImageResource(resid);
					alert.setView(iv);
				}
				alert.create().show();	
			}
			
		});
	}
	
	public void search(){
		search_abb.clear();
		if(state == SORT_ALL){
			for(int i = 0; i < game_abb.size(); i++){
				if(isTextCheck(et_name.getText().toString(), game_abb.get(i).name, game_abb.get(i).text)){
					search_abb.add(game_abb.get(i));
				}	
			}
		}else if(state == SORT_CHAMP){
			for(int i = 0; i < game_abb.size(); i++){
				if(game_abb.get(i).type.equals("champ")){
					if(isTextCheck(et_name.getText().toString(), game_abb.get(i).name, game_abb.get(i).text)){
						search_abb.add(game_abb.get(i));
					}
				}
			}
		}else if(state == SORT_GAME){
			for(int i = 0; i < game_abb.size(); i++){
				if(game_abb.get(i).type.equals("game")){
					if(isTextCheck(et_name.getText().toString(), game_abb.get(i).name, game_abb.get(i).text)){
						search_abb.add(game_abb.get(i));
					}
				}
			}
		}else if(state == SORT_ITEM){
			for(int i = 0; i < game_abb.size(); i++){
				if(game_abb.get(i).type.equals("item")){
					if(isTextCheck(et_name.getText().toString(), game_abb.get(i).name, game_abb.get(i).text)){
						search_abb.add(game_abb.get(i));
					}
				}
			}
		}else if(state == SORT_SYSTEM){
			for(int i = 0; i < game_abb.size(); i++){
				if(game_abb.get(i).type.equals("system")){
					if(isTextCheck(et_name.getText().toString(), game_abb.get(i).name, game_abb.get(i).text)){
						search_abb.add(game_abb.get(i));
					}
				}
			}
		}
	}
	
	public void loadTurm(){
		game_abb.clear();
		AssetManager assetManager = Abbreviation.this.getResources().getAssets();
		AssetInputStream ais = null;
		BufferedReader br = null;
		try {
			ais = (AssetInputStream) assetManager.open("game_abbreviation.txt");
			br = new BufferedReader(new InputStreamReader(ais));
			String line;
			Abbr ab = null;
			while ((line = br.readLine()) != null) {
				StringTokenizer st = new StringTokenizer(line, ";");
				ab = new Abbr();
				ab.type = st.nextToken().trim();
				ab.consonant = st.nextToken();
				ab.image = st.nextToken();
				ab.name = st.nextToken();
				ab.text = st.nextToken();
				game_abb.add(ab);

			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			try {
				ais.close();
				br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	TextWatcher textWatcherInput = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			search();
			adapter.notifyDataSetInvalidated();
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};
	
	public boolean isTextCheck(String ch, String abbr_name, String abbr_text){
		if(!ch.trim().equals("")){
			ch = ch.toLowerCase();
			abbr_name = abbr_name.toLowerCase();
			abbr_text = abbr_text.toLowerCase();
			if(abbr_name.indexOf(ch) != -1 || abbr_text.indexOf(ch) != -1){
				return true;
			}
		}else{
			return true;
		}
		return false;
	}
	
	class AbbrListAdapter extends BaseAdapter{
		Context context;
		private LayoutInflater mInflater;
		public AbbrListAdapter(Context context){
			this.context = context;
			 mInflater = LayoutInflater.from(context);
		}
		@Override
		public int getCount() {
			return search_abb.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}


		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.abbr_row, null); 
				holder = new ViewHolder();
				holder.item_name = (TextView)convertView.findViewById(R.id.item_name); 
				holder.item_text = (TextView)convertView.findViewById(R.id.item_text); 
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			String name = search_abb.get(position).name;
			String text = search_abb.get(position).text;
			if(!et_name.getText().toString().trim().equals("")){
				String ch = et_name.getText().toString().toLowerCase();
				String abbr_name = name.toLowerCase();
				String abbr_text = text.toLowerCase();
				if(abbr_name.indexOf(ch) != -1){
					name = 	name.substring(0, abbr_name.indexOf(ch))+
							"<font color='#ffffff'><u><em>"+
							name.substring(abbr_name.indexOf(ch), abbr_name.indexOf(ch)+ch.length())+
							"</em></u></font>"+
							name.substring(abbr_name.indexOf(ch)+ch.length(), name.length());
				}
				if(abbr_text.indexOf(ch) != -1){
					text = text.substring(0, abbr_text.indexOf(ch))+
							"<font color='#ffffff'><u><em>"+
							text.substring(abbr_text.indexOf(ch), abbr_text.indexOf(ch)+ch.length())+
							"</em></u></font>"+
							text.substring(abbr_text.indexOf(ch)+ch.length(), text.length());
				}
			}
			holder.item_text.setCompoundDrawablePadding(3);
			holder.item_text.setCompoundDrawables(getDrawable(search_abb.get(position).image), null, null, null);
			holder.item_name.setText(Html.fromHtml(name));
			holder.item_text.setText(Html.fromHtml(text));
			return convertView;
		}
	}
	public Drawable getDrawable(String source) {
		if(source.equals("-1")){
			return null;
		}
		int id = getResources().getIdentifier(source, "drawable",getPackageName());
		Drawable d = getResources().getDrawable(id);
		int w = d.getIntrinsicWidth();
		int h = d.getIntrinsicHeight();
		d.setBounds(0, 0, 50, 50); //이미지 크기 설정
		return d;
	}

	class Abbr {
		String type;
		String consonant;
		String image;
		String name;
		String text;
	}
	
	private class ImageGetter implements Html.ImageGetter {
		public Drawable getDrawable(String source) {
			// 문자열 이름으로 리소스 ID를 얻어 온다.
			int id = getResources().getIdentifier(source, "drawable", getPackageName());
			Drawable d = getResources().getDrawable(id);
			int w = d.getIntrinsicWidth();
			int h = d.getIntrinsicHeight();
			d.setBounds(0, 0, w, h);
			return d;
		}
	};
}
